package io.terminus.lego.shinda.web.security.email.filter

import io.terminus.lego.shinda.web.security.email.token.EmailLoginAuthenticationToken
import org.springframework.http.HttpMethod
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 邮箱验证码登录
 * @author wangmeng
 * @date 2018/4/19
 */

class EmailCodeAuthenticationProcessingFilter : AbstractAuthenticationProcessingFilter {
    var PARAMTER_KEY_EMAIL = "email"
    var PARAMTER_KEY_CODE = "verificationCode"

    constructor() : super(AntPathRequestMatcher("/login-email", HttpMethod.POST.name))


    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
        var email = request.getParameter(PARAMTER_KEY_EMAIL)
        var code = request.getParameter(PARAMTER_KEY_CODE)
        if (email.isNullOrEmpty()) {
            email = ""
        }
        if (code.isNullOrEmpty()) {
            code = ""
        }
        email = email.trim()
        val authRequest = EmailLoginAuthenticationToken(email, code)
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest)

        return this.authenticationManager.authenticate(authRequest)
    }

    private fun setDetails(request: HttpServletRequest, authRequest: EmailLoginAuthenticationToken) {
        authRequest.details = authenticationDetailsSource.buildDetails(request)
    }

}